<template>
  <div>
    <Row :gutter="10">
      <Col>
      <Card>
        <div class="live_wrapper clearfix"
             style="margin-top: 10px">
          <Input v-model="filter.name"
                 @on-search="search"
                 search
                 enter-button="搜索"
                 placeholder="请输入分类名称"
                 style="display:inline-table; width: 210px; margin-right: 10px; float:left; " />
          <Button type="primary"
                  @click.stop="addCate()"
                  style="width: 80px;height: 34px;font-size: 14px; margin-right: 10px; margin-top: 1px; float:left;">添加</Button>
          <Button type="primary"
                  @click.stop="exportData()"
                  style="float:left; width: 80px;height: 34px;font-size: 14px; margin-top: 1px;">导出</Button>
        </div>
        <p class="admin_title">
          全部分类
        </p>
        <Row class="margin-top-10 table_pattern table_pattern2">
          <Table style="width: calc(100vw - 256px - 36px - 32px)"
                 :loading="loading"
                 :columns="columns"
                 :data="list"></Table>
        </Row>
        <Row class="margin-top-10">
          <Page :total="pagenation.totalPage"
                :page-size="pagenation.perPage"
                :current="pagenation.currentPage"
                show-elevator
                show-total
                @on-change="change"></Page>
        </Row>
      </Card>
      </Col>
    </Row>
    <Modal v-model="edit"
           :title="title"
           width="700px"
           :mask-closable="false"
           class="goods_modal cyj_modal">
      <Form :model="formValidate"
            ref="formValidate"
            :label-width="90">
        <FormItem label="名称"
                  prop="name"
                  class="label_required">
          <Input v-model="formValidate.name"
                 placeholder="请输入分类名称" />
        </FormItem>
        <FormItem label="分类logo"
                  prop="logo"
                  class="label_required">
          <div class="clearfix live_cover">
            <div style="float: left;margin-right: 18px;">
              <template>
                <div class="demo-upload-list"
                     v-if="formValidate.logo">
                  <img :src="formValidate.logo"
                       style='width:100px; height:100px;object-fit: cover;'>
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline"
                          @click.native="handleView(formValidate.logo)"></Icon>
                    <Icon type="ios-trash-outline"
                          @click.native="handleRemove()"></Icon>
                  </div>
                </div>
                <div v-if="formValidate.logo == ''">
                  <div class="no_pic">
                    <img src="../../assets/images/expo/pic2.png"
                         alt=""
                         width="24" />
                  </div>
                </div>
              </template>
            </div>
            <Upload ref="upload"
                    :show-upload-list="false"
                    action="https://up.qiniup.com"
                    :on-format-error="handleFormatError"
                    :on-progress="handleProgress"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :format="['jpg', 'png', 'jpeg']"
                    :data="{token:upload_token}"
                    style="float: left;">
              <Button style="width:80px;height:30px;background:rgba(248,249,250,1);border:1px solid rgba(232,233,237,1);border-radius:2px;">上传文件</Button>
              <p style="color:#999;margin-top: 8px;">建议尺寸: 100*100px，JPG、PNG格式</p>
            </Upload>
          </div>
        </FormItem>
        <FormItem label="排序"
                  prop="sort"
                  class="label_required">
          <Input v-model="formValidate.sort"
                 placeholder="请输入排序值" />
          <span style="color:#f00">数值越大优先显示</span>
        </FormItem>
        <FormItem>
          <Button :loading="saving"
                  type="primary"
                  @click="handleSubmit"
                  style="width: 90px;height: 35px;border-radius: 0;font-size: 14px; margin-left:180px">提交</Button>
        </FormItem>
      </Form>
    </Modal>
    <Modal title="查看图片"
           v-model="visible">
      <img :src="imgName"
           v-if="visible"
           style="width: 100%">
    </Modal>
  </div>
</template>
<script>

import { getQiniu, goodCateList, editGoodCate, changeGoodCateStatus } from '@/api/main'
export default {
  data () {
    return {
      pagenation: {},
      columns: [
        {
          key: 'name',
          title: '分类名称',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.name)
          },
        },
        {
          key: 'logo',
          title: '分类logo',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              {
                style: {
                  backgroundImage: 'url(' + params.row.logo + ')',
                  width: '70px',
                  height: '70px',
                  objectFit: 'cover',
                  margin: '10px auto',
                  position: 'relative',
                  cursor: 'pointer',
                  backgroundSize: 'cover',
                },
                on: {
                  click: e => {
                    this.handleView(params.row.logo)
                  },
                },
              }
            )
          },
        },
        {
          key: 'sort',
          title: '排序',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.sort)
          },
        },
        {
          key: 'status',
          title: '状态',
          align: 'center',
          render: (h, params) => h('i-switch', {
            props: {
              value: params.row.status,
              size: 'large',
              'true-value': 1,
              'false-value': 0
            },
            on: {
              'on-change': () => {
                let status = params.row.status ? 0 : 1
                this.changeGoodCateStatus(params.row.id, status)
              }
            }
          }, [
            h('span', {
              slot: 'open',
              domProps: {
                innerHTML: '启用'
              }
            }),
            h('span', {
              slot: 'close',
              domProps: {
                innerHTML: '禁用'
              }
            })
          ]
          )
        },
        {
          key: 'created_time',
          title: '创建时间',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.created_time)
          },
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  style: {
                    marginBottom: '5px',
                    marginRight: '5px',
                    border: 0,
                    background: 'transparent',
                    fontSize: '14px',
                    color: '#377EEF'
                  },
                  on: {
                    click: () => {
                      this.editCate(params.row)
                    },
                  },
                },
                '编辑',
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    title: '您确定要删除该分类吗?',
                    transfer: true,
                  },
                  on: {
                    'on-ok': () => {
                      this.changeGoodCateStatus(params.row.id, -1)
                    },
                  },
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        margin: '0 5px 5px 0',
                        border: 0,
                        background: 'transparent',
                        fontSize: '14px',
                        color: '#377EEF'
                      },
                      props: {
                        placement: 'top',
                      }
                    },
                    '删除',
                  ),
                ],
              ),
            ])
          },
        },
      ],
      list: [],
      loading: true,
      edit: false,
      filter: {
        page: 0,
        page_size: 20,
        name: '',
      },
      formValidate: {
        id: 0,
        name: '',
        logo: '',
        sort: 0,
        status: '1',
      },
      title: '添加分类',
      saving: false,
      upload_token: '',
      imgName: '',
      visible: false,
      isSubmiting: false,
    }
  },
  methods: {
    change: function (page) {
      this.loading = true
      this.filter.page = page - 1
      this.getgoodCateList()
    },
    search: function () {
      this.filter.page = 0
      this.getgoodCateList()
    },
    addCate: function () {
      this.formValidate.id = 0
      this.formValidate.logo = ''
      this.formValidate.cover = ''
      this.title = '添加分类'
      this.handleReset('formValidate')
      this.edit = true
    },
    handleReset (name) {
      this.$refs[name].resetFields()
    },
    editCate: function (obj) {
      this.formValidate = Object.assign({}, obj)
      this.formValidate.status = this.formValidate.status.toString()
      this.title = '编辑分类'
      this.edit = true
    },
    changeGoodCateStatus (id, status) {
      let obj = {}
      obj.id = id
      obj.status = status
      changeGoodCateStatus(obj).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
          this.getgoodCateList()
        } else {
          this.$Message.success(res.text)
        }
      })
    },
    handleSubmit () {
      let _this = this
      if (this.formValidate.name == '') {
        this.$Message.error("请输入分类名称"); return;
      }
      if (this.formValidate.logo == '') {
        this.$Message.error("请上传分类logo"); return;
      }
      if (this.isSubmiting) {
        return
      }
      this.isSubmiting = true
      editGoodCate(this.formValidate).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
          this.edit = false
          this.getgoodCateList()
        } else {
          this.$Message.error(res.text)
        }
        setTimeout(() => {
          this.isSubmiting = false
        }, 1000);
      })
    },
    handleFormatError (file) {
      this.$Message.error('文件 ' + file.name + ' 格式不正确，请选择图片文件。')
    },
    handleProgress (event, file) { },
    handleSuccess (event, file, fileList) {
      this.formValidate.logo = file.response.domain + file.response.key
    },
    handleError (event, file) { },
    handleView (img_url) {
      this.imgName = img_url
      this.visible = true
    },
    handleRemove (type) {
      this.formValidate.logo = ''
    },
    getgoodCateList () {
      goodCateList(this.filter).then(res => {
        if (res.code == 0) {
          this.list = res.data
          this.loading = false
          this.pagenation.currentPage = parseInt(res.currentPage) + 1
          this.pagenation.totalPage = parseInt(res.totalPage)
          this.pagenation.perPage = parseInt(res.perPage)
        }
      })
    },
    async init () {
      let qiniu = await getQiniu()
      this.upload_token = qiniu.token
      this.qiniu_url = qiniu.url
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    exportData () {
      let _this = this
      _this.filter.page = 0
      _this.filter.page_size = 500
      _this.export_list = []
      _this.export()
    },
    export () {
      let _this = this
      goodCateList(this.filter).then(res => {
        if (res.code == 0) {
          if (res.data.length) {
            _this.export_list.push.apply(_this.export_list, res.data)
            _this.filter.page++
            _this.export()
          } else {
            _this.filter.page_size = 20
            const { export_json_to_excel } = require('../../excel/Export2Excel');
            const tHeader = ['名称', '排序', '状态', '创建时间'];
            const filterVal = ['name', 'sort', 'status_name', 'created_time'];
            const data = _this.formatJson(filterVal, _this.export_list)
            export_json_to_excel(tHeader, data, '商品分类信息')
          }
        }
      })
    },
  },
  mounted () {
    this.init();
    this.getgoodCateList()
  }
}
</script>
<style>
.edui-notadd .edui-dialog {
	z-index: 2005 !important;
}
.edui-notadd {
	z-index: 2002 !important;
}
</style>
<style scoped lang="less">
/deep/ .edui-notadd .edui-dialog {
	z-index: 5000 !important;
}
/deep/ input::-webkit-input-placeholder {
	color: rgba(153, 153, 153, 0.47) !important;
	font-size: 14px !important;
}
/deep/ input::-moz-placeholder {
	color: rgba(153, 153, 153, 0.47) !important;
	font-size: 14px !important;
}
/deep/ input:-moz-placeholder {
	color: rgba(153, 153, 153, 0.47) !important;
	font-size: 14px !important;
}
/deep/ input:-ms-input-placeholder {
	color: rgba(153, 153, 153, 0.47) !important;
	font-size: 14px !important;
}
</style>
